package com.oreilly.ez.fileserver.base;

import com.oreilly.ez.fileserver.util.JwtUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LoginInterceptor implements HandlerInterceptor {


    /**
     * 在请求被处理之前调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查每个到来的请求对应的session域中是否有登录标识
//        Object loginName = request.getSession().getAttribute("loginName");
//        if (null == loginName || !(loginName instanceof String)) {
//            // 未登录，重定向到登录页
//            response.sendRedirect("/");
//            return false;
//        }
//        String userName = (String) loginName;
//        System.out.println("当前用户已登录，登录的用户名为： " + userName);
//        return true;

// 从 http 请求头中取出 token
        String token = request.getHeader("x-token");

        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        String requestURI = request.getRequestURI();
        System.out.println("requestURI =" + requestURI);

        if(requestURI.startsWith("/swagger") || requestURI.startsWith("/webjars")){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        System.out.println("##method =" + method);
        //检查是否有LoginToken注释，有则跳过认证
//        if (method.isAnnotationPresent(LoginToken.class)) {
//            LoginToken loginToken = method.getAnnotation(LoginToken.class);
//            if (loginToken.required()) {
//                return true;
//            }
//        }

        //检查有没有需要用户权限的注解
//        if (method.isAnnotationPresent(CheckToken.class)) {
//            CheckToken checkToken = method.getAnnotation(CheckToken.class);
//            if (checkToken.required()) {
//                // 执行认证
//                if (token == null) {
//                    throw new RuntimeException("无token，请重新登录");
//                }
//                // 获取 token 中的 user id
//                String userId;
//                try {
//                    userId = JWT.decode(token).getClaim("id").asString();
//                } catch (JWTDecodeException j) {
//                    throw new RuntimeException("访问异常！");
//                }
//                User user = userService.findUserById(userId);
//                if (user == null) {
//                    throw new RuntimeException("用户不存在，请重新登录");
//                }
//                Boolean verify = JwtUtil.isVerify(token, user);
//                if (!verify) {
//                    throw new RuntimeException("非法访问！");
//                }
//                return true;
//            }
//        }


        // 执行认证
        if (token == null) {

            Cookie[] cookies = request.getCookies();
            if(cookies != null ){
                for (Cookie cookie : cookies) {
                    if(cookie.getName().equals("x-token")){
                        token = cookie.getValue();
                    }
                }
            }
        }

        if (token == null) {

            throw new RuntimeException("无token，请重新登录");
        }
        // 获取 token 中的 user id
        // 与数据库的进行对比
//        String userId;
//        try {
//            userId = JWT.decode(token).getClaim("passcode").asString();
//        } catch (JWTDecodeException j) {
//            throw new RuntimeException("访问异常！");
//        }

        Boolean verify = JwtUtil.isVerify(token);
        if (!verify) {
            throw new RuntimeException("非法访问！");
        }

        return true;

    }

    /**
     * 在请求被处理后，视图渲染之前调用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个请求结束后调用
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
